#!/bin/bash

if [ x$EXEC = x ]; then
	EXEC=exact-imp
fi

mkdir tmp 2>/dev/null

FIRST=`cat data/$1.anot | head -n 1 | cut -f 1 -d ' '`
LAST=`cat data/$1.anot | tail -n 1 | cut -f 1 -d ' '`

let FIRST=FIRST-4000
let FIRST=(FIRST/250)*250
let LAST=LAST+350
let LAST=(LAST/250)*250

echo Data range - $FIRST to $LAST
let DIFF=LAST-FIRST

#if [ $DIFF -gt 8000 ]; then
#    DIFF=8000
#    let LAST=FIRST+DIFF
#fi

echo Extracting the data - $FIRST to $LAST

cd data
../extract $1 $FIRST $LAST 0 > ../tmp/tmp3.$2.0
../extract $1 $FIRST $LAST 1 > ../tmp/tmp3.$2.1
cd ..

# 2-lead delineation
ARG="tmp/tmp3.$2.0 tmp/tmp3.$2.1"
# lead 0 delineation
#ARG="tmp/tmp3.$2.0 0"
# lead 1 delineation
#ARG="tmp/tmp3.$2.1 0"

if [ a$3 == ashimmer ]; then
    PROG=./senddata
else
    PROG=./$EXEC
    if [ a$2 == astat ]; then
	MAX=`cat tmp/tmp3.$2.0 tmp/tmp3.$2.1 | tr -d '-' | sort -n | tail -n 1`
	ARG="$ARG $MAX" # Sample multiplier
    else
	ARG="$ARG 2048" # Sample multiplier
    fi
fi

echo Running $PROG $ARG

#valgrind --tool=memcheck 

#ARG="tmp/tmp3.$2.1 0"

$PROG $ARG data/$1.anot $FIRST > tmp/tmp4.$2 2>tmp/tmp4.debug.$2

if [ a$2 == astat ]; then
	rm tmp/val.result.$2
	rm tmp/errors.$2
	rm tmp/sanity.$2
fi

echo $1 >> tmp/sanity.$2
grep -A 5 -B 5 "@@@@@" tmp/tmp4.debug.$2 >> tmp/sanity.$2

echo "Results:"
grep "^#VALIDATION" tmp/tmp4.$2
grep "^#VALIDATION" tmp/tmp4.$2 | sed -e "s/.*: \(.*\)/\1/" >> tmp/val.result.$2
grep "total time" tmp/tmp4.debug.$2 | sed -e "s/.*total time=\(.*\) ms.*/time = [ time (1000*$DIFF\/250)\/\1 ]; #$1/" >> tmp/val.result.$2
echo $1 >> tmp/errors.$2
echo "False negatives:"
grep "^#FN" tmp/tmp4.$2
grep "^#FN" tmp/tmp4.$2 >> tmp/errors.$2
echo "False positives:"
grep "^#FP" tmp/tmp4.$2
grep "^#FP" tmp/tmp4.$2 >> tmp/errors.$2

if [ a$2 == astat ]; then
    mv tmp/val.result.$2 tmp/val.result
    mv tmp/errors.$2 tmp/errors
    octave -q validate.octave
fi
